/**
 * 积分管理工具类
 * 提供积分相关的本地存储和操作方法
 */

class PointsManager {
  constructor() {
    this.baseStorageKey = 'userPointsData'
  }

  /**
   * 获取当前用户ID（用于数据隔离）
   */
  getCurrentUserId() {
    try {
      // 优先从 currentUser 获取
      const currentUser = uni.getStorageSync('currentUser')
      if (currentUser) {
        const user = typeof currentUser === 'string' ? JSON.parse(currentUser) : currentUser
        if (user && (user.id || user.email)) {
          return user.id || user.email
        }
      }
      
      // 如果 currentUser 不存在，尝试从 user_token 或 userInfo 获取
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        const user = typeof userInfo === 'string' ? JSON.parse(userInfo) : userInfo
        if (user && (user.id || user.email)) {
          return user.id || user.email
        }
      }
      
      // 如果都没有，检查是否有 token（说明已登录但用户信息可能未加载）
      const token = uni.getStorageSync('user_token')
      if (token) {
        // 已登录但用户信息未加载，返回临时ID
        return 'temp_' + Date.now()
      }
      
      return 'anonymous'
    } catch (error) {
      console.error('获取用户ID失败:', error)
      return 'anonymous'
    }
  }

  /**
   * 获取存储键（按用户ID隔离）- 已废弃，现在使用 users 数组
   * 保留此方法用于向后兼容和迁移
   */
  getStorageKey() {
    const userId = this.getCurrentUserId()
    return `${this.baseStorageKey}_${userId}`
  }

  /**
   * 从 users 数组中获取当前用户的积分数据
   */
  getPointsData() {
    try {
      const userId = this.getCurrentUserId()
      if (userId === 'anonymous') {
        return null
      }

      // 从 users 数组中查找当前用户
      const usersData = uni.getStorageSync('users')
      if (!usersData) {
        return null
      }

      const users = JSON.parse(usersData)
      const currentUser = users.find(u => {
        const uId = u.id || u.email
        return uId === userId
      })

      if (currentUser && currentUser.pointsData) {
        return currentUser.pointsData
      }

      return null
    } catch (error) {
      console.error('获取积分数据失败:', error)
      return null
    }
  }

  /**
   * 保存积分数据到 users 数组中
   */
  savePointsData(data) {
    try {
      const userId = this.getCurrentUserId()
      if (userId === 'anonymous') {
        console.warn('未登录用户无法保存积分数据')
        return false
      }

      // 获取 users 数组
      const usersData = uni.getStorageSync('users')
      let users = []
      if (usersData) {
        users = JSON.parse(usersData)
      }

      // 查找当前用户
      const userIndex = users.findIndex(u => {
        const uId = u.id || u.email
        return uId === userId
      })

      const pointsData = {
        ...data,
        userId: userId, // 保存用户ID用于验证
        lastUpdate: new Date().toISOString()
      }

      if (userIndex !== -1) {
        // 更新现有用户的积分数据
        users[userIndex].pointsData = pointsData
      } else {
        // 如果用户不存在，创建新用户（这种情况应该很少见）
        console.warn('用户不存在于 users 数组中，创建新用户记录')
        const currentUser = uni.getStorageSync('currentUser')
        let userInfo = {}
        if (currentUser) {
          userInfo = JSON.parse(currentUser)
        }
        users.push({
          ...userInfo,
          pointsData: pointsData
        })
      }

      // 保存更新后的 users 数组
      uni.setStorageSync('users', JSON.stringify(users))

      // 同时更新 currentUser（如果存在）
      const currentUser = uni.getStorageSync('currentUser')
      if (currentUser) {
        const userInfo = JSON.parse(currentUser)
        userInfo.pointsData = pointsData
        uni.setStorageSync('currentUser', JSON.stringify(userInfo))
      }

      return true
    } catch (error) {
      console.error('保存积分数据失败:', error)
      return false
    }
  }

  /**
   * 获取当前积分
   */
  getCurrentPoints() {
    const data = this.getPointsData()
    return data ? data.points || 0 : 0
  }

  /**
   * 获取用户等级
   */
  getUserLevel() {
    const data = this.getPointsData()
    return data ? data.level || 1 : 1
  }

  /**
   * 获取等级进度
   */
  getLevelProgress() {
    const data = this.getPointsData()
    return data ? data.levelProgress || 0 : 0
  }

  /**
   * 检查签到状态
   */
  getCheckInStatus() {
    // 检查是否已登录
    const token = uni.getStorageSync('user_token')
    if (!token) {
      return false
    }
    
    const data = this.getPointsData()
    if (!data) {
      return false
    }
    
    // 验证数据是否属于当前用户（防止切换账号后读取到其他用户的数据）
    const currentUserId = this.getCurrentUserId()
    if (data.userId && data.userId !== currentUserId && currentUserId !== 'anonymous') {
      console.warn('签到状态数据不属于当前用户，重置状态', {
        dataUserId: data.userId,
        currentUserId: currentUserId
      })
      return false
    }
    
    // 检查是否需要重置签到状态（新的一天）
    if (this.shouldResetCheckIn(data)) {
      this.resetCheckInStatus()
      return false
    }
    
    return data.checkInStatus || false
  }
  
  /**
   * 检查是否需要重置签到状态
   */
  shouldResetCheckIn(data) {
    // 如果签到状态为 false，不需要重置
    if (!data.checkInStatus) {
      return false
    }
    
    // 如果没有上次签到日期，但状态为已签到，需要重置（异常情况）
    if (!data.lastCheckInDate) {
      console.warn('签到状态异常：已签到但无签到日期，重置状态')
      return true
    }
    
    try {
      const lastCheckInDate = new Date(data.lastCheckInDate)
      const today = new Date()
      
      // 验证日期是否有效
      if (isNaN(lastCheckInDate.getTime())) {
        console.warn('签到日期格式无效，重置状态')
        return true
      }
      
      // 比较日期（忽略时间），使用本地时区
      const lastCheckInDay = lastCheckInDate.getDate()
      const lastCheckInMonth = lastCheckInDate.getMonth()
      const lastCheckInYear = lastCheckInDate.getFullYear()
      
      const todayDay = today.getDate()
      const todayMonth = today.getMonth()
      const todayYear = today.getFullYear()
      
      // 如果不是同一天，需要重置
      const isDifferentDay = !(lastCheckInDay === todayDay && 
                               lastCheckInMonth === todayMonth && 
                               lastCheckInYear === todayYear)
      
      if (isDifferentDay) {
        console.log('检测到新的一天，重置签到状态', {
          lastCheckIn: `${lastCheckInYear}-${lastCheckInMonth + 1}-${lastCheckInDay}`,
          today: `${todayYear}-${todayMonth + 1}-${todayDay}`
        })
      }
      
      return isDifferentDay
    } catch (error) {
      console.error('检查签到日期失败:', error)
      // 出错时重置状态，确保用户可以重新签到
      return true
    }
  }
  
  /**
   * 重置签到状态
   */
  resetCheckInStatus() {
    const currentData = this.getPointsData()
    if (!currentData) {
      return false
    }
    
    const newData = {
      ...currentData,
      checkInStatus: false,
      lastCheckInDate: null // 清除签到日期
    }
    
    // 确保保存数据
    const saved = this.savePointsData(newData)
    if (saved) {
      console.log('签到状态已重置并保存')
    } else {
      console.error('重置签到状态失败：保存数据失败')
    }
    return saved
  }

  /**
   * 计算等级和进度
   */
  calculateLevelAndProgress(points) {
    const level = Math.floor(points / 100) + 1
    const levelPoints = points % 100
    const progress = Math.floor((levelPoints / 100) * 100)
    return { level, progress }
  }

  /**
   * 添加积分
   */
  addPoints(points, reason = '获得积分') {
    // 检查是否已登录
    const token = uni.getStorageSync('user_token')
    if (!token) {
      console.warn('未登录用户无法获得积分')
      return false
    }
    
    const currentData = this.getPointsData()
    if (!currentData) {
      // 初始化数据
      const newPoints = points
      const { level, progress } = this.calculateLevelAndProgress(newPoints)
      const newData = {
        points: newPoints,
        level: level,
        levelProgress: progress,
        checkInStatus: false,
        recentActivities: [{
          id: Date.now(),
          icon: '💎',
          title: reason,
          time: '刚刚',
          points: points,
          type: 'earn'
        }]
      }
      this.savePointsData(newData)
      return true
    }

    const newPoints = currentData.points + points
    const { level, progress } = this.calculateLevelAndProgress(newPoints)
    
    // 添加活动记录
    const newActivity = {
      id: Date.now(),
      icon: '💎',
      title: reason,
      time: '刚刚',
      points: points,
      type: 'earn'
    }
    
    const activities = currentData.recentActivities || []
    activities.unshift(newActivity)
    
    // 限制活动记录数量
    if (activities.length > 10) {
      activities.splice(10)
    }

    const newData = {
      ...currentData,
      points: newPoints,
      level: level,
      levelProgress: progress,
      recentActivities: activities
    }

    return this.savePointsData(newData)
  }

  /**
   * 消费积分
   */
  spendPoints(points, reason = '消费积分') {
    const currentData = this.getPointsData()
    if (!currentData || currentData.points < points) {
      return false
    }

    const newPoints = currentData.points - points
    const { level, progress } = this.calculateLevelAndProgress(newPoints)
    
    // 添加活动记录
    const newActivity = {
      id: Date.now(),
      icon: '🛒',
      title: reason,
      time: '刚刚',
      points: points,
      type: 'spend'
    }
    
    const activities = currentData.recentActivities || []
    activities.unshift(newActivity)
    
    // 限制活动记录数量
    if (activities.length > 10) {
      activities.splice(10)
    }

    const newData = {
      ...currentData,
      points: newPoints,
      level: level,
      levelProgress: progress,
      recentActivities: activities
    }

    return this.savePointsData(newData)
  }

  /**
   * 设置签到状态
   */
  setCheckInStatus(status) {
    const currentData = this.getPointsData()
    if (!currentData) {
      return false
    }

    const newData = {
      ...currentData,
      checkInStatus: status,
      // 如果签到成功，记录签到日期
      lastCheckInDate: status ? new Date().toISOString() : currentData.lastCheckInDate
    }

    return this.savePointsData(newData)
  }

  /**
   * 获取最近活动
   */
  getRecentActivities() {
    const data = this.getPointsData()
    return data ? data.recentActivities || [] : []
  }

  /**
   * 清除当前用户的积分数据
   */
  clearAllData() {
    try {
      const userId = this.getCurrentUserId()
      if (userId === 'anonymous') {
        return false
      }

      // 从 users 数组中清除当前用户的积分数据
      const usersData = uni.getStorageSync('users')
      if (usersData) {
        const users = JSON.parse(usersData)
        const userIndex = users.findIndex(u => {
          const uId = u.id || u.email
          return uId === userId
        })

        if (userIndex !== -1) {
          delete users[userIndex].pointsData
          uni.setStorageSync('users', JSON.stringify(users))
        }
      }

      // 同时清除 currentUser 中的积分数据
      const currentUser = uni.getStorageSync('currentUser')
      if (currentUser) {
        const userInfo = JSON.parse(currentUser)
        delete userInfo.pointsData
        uni.setStorageSync('currentUser', JSON.stringify(userInfo))
      }

      return true
    } catch (error) {
      console.error('清除积分数据失败:', error)
      return false
    }
  }

  /**
   * 清除所有用户的积分数据（用于退出登录时清理）
   */
  clearAllUsersData() {
    try {
      // 从 users 数组中清除所有用户的积分数据
      const usersData = uni.getStorageSync('users')
      if (usersData) {
        const users = JSON.parse(usersData)
        users.forEach(user => {
          delete user.pointsData
        })
        uni.setStorageSync('users', JSON.stringify(users))
      }

      // 同时清除 currentUser 中的积分数据
      const currentUser = uni.getStorageSync('currentUser')
      if (currentUser) {
        const userInfo = JSON.parse(currentUser)
        delete userInfo.pointsData
        uni.setStorageSync('currentUser', JSON.stringify(userInfo))
      }

      // 兼容旧版本：清除所有以 userPointsData_ 开头的存储项
      const storageInfo = uni.getStorageInfoSync()
      if (storageInfo && storageInfo.keys) {
        storageInfo.keys.forEach(key => {
          if (key.startsWith(this.baseStorageKey + '_')) {
            uni.removeStorageSync(key)
          }
        })
      }

      return true
    } catch (error) {
      console.error('清除所有用户积分数据失败:', error)
      return false
    }
  }
}

// 创建单例实例
const pointsManager = new PointsManager()

export default pointsManager
